import {
  ProCard,
  ProFormGroup,
  ProFormInstance,
} from '@ant-design/pro-components';
import {
  ProForm,
  ModalForm,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormDatePicker,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import { history, useRequest } from 'umi';
import {
  message,
  Button,
  Card,
  Breadcrumb,
  Collapse,
  Upload,
  Descriptions,
  Space,
  Modal,
  Table,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import type { UploadProps } from 'antd';
import {
  PlusOutlined,
  UploadOutlined,
  FileSearchOutlined,
  InboxOutlined,
} from '@ant-design/icons';
import {
  getLabelAdapter,
  isPassAdapter,
  TitleAdapter,
} from '../../commons/Adapter';
import TbaleExplainMap from '@/components/TipsMap';
import moment from 'moment';
const { Panel } = Collapse;
const { Dragger } = Upload;

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export default () => {
  const formRef = useRef<ProFormInstance>();
  const addPersonFrom = useRef<ProFormInstance>();
  const [paperId, setPaperId] = useState('');
  const [filedDisable, setFiledDisable] = useState({
    username: true,
    technicalGrade: true,
    technicalName: true,
    type: true,
  });
  const [proTableData, setProTableData] = useState([]);
  const [updateStatus, setUpdateStatus] = useState(false);
  const [newpath, setNewPath] = useState();

  const [modalDataSource, setModalDataSource] = useState([]); //modal的数据源
  const [selectKeys, setSelectKeys] = useState([]); //modal checkbox默认选中
  const [saveType, setSaveType] = useState(''); //modal 点击确认 调用新增、更新还是暂存接口

  const props: UploadProps = {
    name: 'file',
    action: 'http://10.1.40.84:9993/common/uploadFile',
    headers: {
      Authorization: localStorage.getItem('token') || '',
    },
    maxCount: 1,
    accept: '.docx,.doc,.pdf,.xls',
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        formRef.current?.setFieldsValue({
          annexPath: info?.file?.response.data,
        });
        message.success(`${info.file.name} 上传成功！`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败！`);
      }
    },
  };
  //根据ID查询论文详情
  const findPaperDetailById = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/patent/findPatentDetailById',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(result);
        setProTableData(result.userCommonRelations);
        // console.log(JSON.parse(result));
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      // formatResult: res => res
      manual: true,
    },
  );
  //更新论文
  const updatePaper = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/patent/updatePatent',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        if (result.code === 200) {
          history.push('/LabAchievements/ScientificResearch/GrantPatent');
        } else {
          message.error(result.msg);
        }
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      formatResult: (res) => res,
      manual: true,
    },
  );
  //新增论文
  const addPaper = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/patent/addPatent',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        if (result.code === 200) {
          history.push('/LabAchievements/ScientificResearch/GrantPatent');
        } else {
          message.error(result.msg);
        }
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      formatResult: (res) => res,
      manual: true,
    },
  );
  //查找所有标签
  const getAllLabel = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/getAllLabel',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(result);
        // history.push('/LabAchievements/ScientificResearch/Paper');
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      // formatResult: res => res
      // manual: true,
    },
  );
  //添加标签
  const addLabelDetail = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/addLabelDetail',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(result);
        getAllLabel.run();
        message.success('添加成功');
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      // formatResult: res => res
      manual: true,
    },
  );
  //根据名字查找人详细信息
  const findOneUserInfoDetailByName = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/user/findOneUserInfoDetailByName',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );
  //根据职称等级选择职称名称
  const getLike = useRequest(
    (data = { field: 'technicalName', level: '正高级' }) => {
      return {
        url: 'http://10.1.40.84:9993/getLike',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
  );
  //获取所有方向/direction/findAllDirection
  const findAllDirection = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/direction/findAllDirection',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(result);
        // setProTableData(result.userCommonRelations);
      },
      formatResult: (res) => {
        let datatemp: any = [];
        res.data.map((item: any) => {
          let dataObj = {
            key: item.directionName,
            value: item.directionName,
          };
          datatemp.push(dataObj);
        });
        return datatemp;
      },
      // manual: true,
    },
  );
  //模糊查询国家
  const getCountry = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/getLike',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(result);
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      // formatResult: res => res
      manual: true,
    },
  );
  //
  const addOrUpdatePaperTemp = useRequest(
    (data = {}) => {
      return {
        url: `http://10.1.40.84:9993/patent/addOrUpdateGrantPatentTemp`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        history.push('/LabAchievements/ScientificResearch/GrantPatent');
        console.log(result);
      },
      manual: true,
    },
  );
  //审核
  const updateStatusIpi = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/common/updateStatus',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  //根据userList获取人员列表/user/getUserList
  const getUserList = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/user/getUserList',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
      onSuccess: (result) => {
        console.log(result);
        let resultTemp: any = [];
        result.map((item: any) => {
          resultTemp.push(item.webId);
        });
        console.log(resultTemp);
        setSelectKeys(resultTemp);
      },
    },
  );

  useEffect(() => {
    const paperIdTemp = history.location.pathname.replace(
      '/LabAchievements/ScientificResearch/GrantPatent/',
      '',
    );
    setPaperId(paperIdTemp);
    if (paperIdTemp !== 'new') {
      findPaperDetailById.run({ id: paperIdTemp }).then((e) => {
        const { year, authors, ...formdata2 } = e;
        formRef.current?.setFieldsValue({
          year: year ? moment(year, 'YYYY') : null,
          authors: authors != 'null' && authors ? authors : null,
          ...formdata2,
        });
      });
    }
  }, []);

  const [isModalVisible, setIsModalVisible] = useState(false);
  // const modalForm = useRef<ProFormInstance>();

  const showModal = (value: any) => {
    console.log(value);
    setModalDataSource(value);
    setIsModalVisible(true);
  };

  const handleOk = () => {
    let paramTemp: any = [];
    selectKeys.map((element: any) => {
      paramTemp.push(
        getUserList?.data.filter((item: any) => item.webId === element)[0],
      );
    });
    if (saveType === '暂存') {
      let formRefData: any = formRef.current?.getFieldsValue();
      addOrUpdatePaperTemp.run({
        ...formRefData,
        userCommonRelations: paramTemp,
        id: paperId === 'new' ? null : paperId,
        patentType: '授权专利',
      });
    }
    if (saveType === '新增') {
      let formRefData: any = formRef.current?.getFieldsValue();
      addPaper.run({
        ...formRefData,
        userCommonRelations: paramTemp,
        patentType: '授权专利',
      });
    }
    if (saveType === '更新') {
      let formRefData: any = formRef.current?.getFieldsValue();

      updatePaper
        .run({
          ...formRefData,
          id: paperId,
          userCommonRelations: paramTemp,
        })
        .then(() => {
          if (localStorage.getItem('isEdit') === '审核') {
            updateStatusIpi
              .run({
                tableName: 'GRANT_PATENT',
                ids: [paperId],
                status: 2, //审核通过
                tab: '子方向视角',
                patentType: '授权专利',
              })
              .then(() => {
                history.goBack();
                message.success('操作成功');
              });
          }
        });
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <PageContainer
      header={{
        title: findPaperDetailById?.data?.message ? (
          <div style={{ fontSize: 14, textAlign: 'center', color: 'red' }}>
            拒绝原因：{findPaperDetailById?.data?.message}
          </div>
        ) : null,
        breadcrumb: (
          <Breadcrumb>
            <Breadcrumb.Item>科学研究</Breadcrumb.Item>
            <Breadcrumb.Item>授权专利</Breadcrumb.Item>
            <Breadcrumb.Item>
              {TitleAdapter(
                paperId,
                localStorage.getItem('isEdit'),
                '授权专利',
              )}
            </Breadcrumb.Item>
          </Breadcrumb>
        ),
      }}
      extra={
        <div>
          {localStorage.getItem('isEdit') === '审核' ? (
            <Space>
              <ModalForm
                title="拒绝"
                trigger={<Button key="2">返回成员修改</Button>}
                autoFocusFirstInput
                modalProps={{
                  onCancel: () => console.log('run'),
                  destroyOnClose: true,
                }}
                submitTimeout={2000}
                onFinish={async (values) => {
                  console.log(values);
                  updateStatusIpi
                    .run({
                      tableName: 'GRANT_PATENT',
                      ids: [paperId],
                      status: 3, //拒绝
                      message: values.message,
                      tab: '子方向视角',
                      patentType: '授权专利',
                    })
                    .then(() => {
                      // findPaperDetailById.run({ id: paperId }).then((e) => {
                      //   formRef.current?.setFieldsValue(e);
                      //   setNewPath(e?.annexPath);
                      // });
                      history.goBack();
                      message.success('操作成功');
                    });
                  return true;
                }}
                grid={true}
                initialValues={{ message: findPaperDetailById?.data?.message }}
              >
                <ProForm.Group>
                  <ProFormText
                    name="message"
                    label="拒绝原因"
                    placeholder="请输入拒绝原因"
                    colProps={{ span: 24 }}
                    rules={[{ required: true, message: '请输入拒绝原因' }]}
                  />
                </ProForm.Group>
              </ModalForm>

              <Button
                key="1"
                type="primary"
                onClick={() => {
                  let formRefData: any = formRef.current?.getFieldsValue();
                  if (!formRefData?.annexPath) {
                    message.warning('请上传材料！');
                  } else {
                    if (paperId === 'new') {
                      setSaveType('新增');
                    } else {
                      setSaveType('更新');
                    }
                    getUserList
                      .run({ userList: formRefData.authors })
                      .then((e) => {
                        showModal(e);
                      });
                  }
                }}
              >
                提交管理员审核
              </Button>
            </Space>
          ) : null}
        </div>
      }
      content={
        localStorage.getItem('isEdit') === '查看' ? (
          <Descriptions title="基本信息" layout="horizontal" bordered>
            {localStorage.getItem('identity') === '管理员' ? (
              <>
                <Descriptions.Item label="序号" labelStyle={{ width: 140 }}>
                  {findPaperDetailById?.data?.seq}
                </Descriptions.Item>
                <Descriptions.Item label="年度" labelStyle={{ width: 140 }}>
                  {findPaperDetailById?.data?.year}
                </Descriptions.Item>
              </>
            ) : null}
            <Descriptions.Item label="专利号" labelStyle={{ width: 120 }}>
              {findPaperDetailById?.data?.patentId}
            </Descriptions.Item>
            <Descriptions.Item label="专利名称" span={3}>
              {findPaperDetailById?.data?.patentName}
            </Descriptions.Item>
            <Descriptions.Item label="专利类别" span={3}>
              {findPaperDetailById?.data?.patentChildType}
            </Descriptions.Item>
            <Descriptions.Item label="专利完成人" span={3}>
              {findPaperDetailById?.data?.authors}
            </Descriptions.Item>
            {localStorage.getItem('identity') === '管理员' ? (
              <Descriptions.Item label="所属研究方向">
                {findPaperDetailById?.data?.researchDire}
              </Descriptions.Item>
            ) : null}
            <Descriptions.Item label="授权公告日">
              {findPaperDetailById?.data?.patentTime}
            </Descriptions.Item>
            <Descriptions.Item label="完成情况">
              {findPaperDetailById?.data?.patentState}
            </Descriptions.Item>
            <Descriptions.Item label="获准国家">
              {findPaperDetailById?.data?.country}
            </Descriptions.Item>
            <Descriptions.Item
              label="授权专利标签"
              span={localStorage.getItem('identity') !== '管理员' ? 0 : 2}
            >
              {getLabelAdapter(
                getAllLabel?.data,
                findPaperDetailById?.data?.labels,
              )}
            </Descriptions.Item>
            <Descriptions.Item label="专利简介" span={3}>
              {findPaperDetailById?.data?.remarks}
            </Descriptions.Item>
          </Descriptions>
        ) : (
          <ProForm
            onFinish={async (values) => {
              // await waitTime(2000);
              if (!values?.annexPath) {
                message.warning('请上传材料！');
              } else {
                if (paperId === 'new') {
                  setSaveType('新增');
                } else {
                  setSaveType('更新');
                }
                getUserList.run({ userList: values.authors }).then((e) => {
                  showModal(e);
                });
              }
            }}
            formRef={formRef}
            formKey="base-form-use-demo"
            autoFocusFirstInput
            submitter={{
              render: (props, dom) => (
                <FooterToolbar>
                  {localStorage.getItem('isEdit') === '审核' ? null : (
                    <>
                      {paperId === 'new' ||
                      findPaperDetailById?.data?.isPass + '' === '-1' ? (
                        <Button
                          onClick={() => {
                            setSaveType('暂存');
                            let values = props.form?.getFieldsValue();
                            if (values.authors) {
                              getUserList
                                .run({ userList: values.authors })
                                .then((e) => {
                                  showModal(e);
                                })
                                .catch((e) => message.error('作者填写有误'));
                            } else {
                              addOrUpdatePaperTemp.run({
                                ...values,
                                userCommonRelations: proTableData,
                                id: paperId === 'new' ? null : paperId,
                                patentType: '授权专利',
                              });
                            }
                          }}
                        >
                          暂存
                        </Button>
                      ) : null}
                      <Button
                        type="primary"
                        onClick={() => {
                          formRef.current?.submit();
                        }}
                      >
                        提交
                      </Button>
                    </>
                  )}
                </FooterToolbar>
              ),
            }}
            grid={true}
            rowProps={{
              gutter: 16,
            }}
          >
            <ProFormText
              name={'annexPath'}
              label={'材料地址'}
              placeholder="待审核"
              hidden
            />
            <ProFormText
              width="sm"
              name="annexPath"
              label="附件链接"
              hidden
              colProps={{ span: 4 }}
            />
            <ProForm.Group title={'基本信息'}>
              <ProFormText
                disabled
                name="seq"
                label="序号"
                colProps={{ span: 4 }}
                hidden={true}
              />

              <ProFormText
                name="patentName"
                label="专利名称"
                colProps={{
                  span: 6,
                }}
                disabled={updateStatus}
                rules={[{ required: true, message: '请输入' }]}
              />
              <ProFormText
                name="authors"
                label="所有完成人（学生姓名后标*，外单位人员名字后标#）"
                placeholder="请输入，以英文逗号分割"
                colProps={{
                  span: 6,
                }}
                disabled={updateStatus}
                rules={[{ required: true, message: '请输入' }]}
              />
              <ProFormSelect
                options={[
                  {
                    value: '独立完成',
                    label: '独立完成',
                  },
                  {
                    value: '第一完成人(非独立完成)',
                    label: '第一完成人(非独立完成)',
                  },
                  {
                    value: '非第一完成人(非独立完成)',
                    label: '非第一完成人(非独立完成)',
                  },
                ]}
                name="patentState"
                label="完成情况"
                colProps={{ span: 3 }}
                disabled={updateStatus}
                rules={[{ required: true, message: '请选择' }]}
                hidden={localStorage.getItem('identity') !== '管理员'}
              />
            </ProForm.Group>
            <ProForm.Group title="详细内容">
              <ProFormDatePicker.Year
                name="year"
                label="年度"
                colProps={{ span: 3 }}
                disabled={updateStatus}
                hidden={localStorage.getItem('identity') !== '管理员'}
              />
              <ProFormText
                name="patentId"
                label="专利号"
                colProps={{ span: 3 }}
                disabled={updateStatus}
                rules={[{ required: true, message: '请输入' }]}
              />

              <ProFormSelect
                options={[
                  {
                    value: '发明专利',
                    label: '发明专利',
                  },
                  {
                    value: '实用新型',
                    label: '实用新型',
                  },
                  {
                    value: '外观设计',
                    label: '外观设计',
                  },
                  {
                    value: '软件制品',
                    label: '软件制品',
                  },
                ]}
                name="patentChildType"
                label="类别"
                colProps={{ span: 3 }}
                disabled={updateStatus}
                rules={[{ required: true, message: '请选择' }]}
              />

              <ProFormSelect.SearchSelect
                name="country"
                label="获准国家"
                fieldProps={{
                  labelInValue: false,
                }}
                rules={[{ required: true, message: '请选择' }]}
                mode={'single'}
                colProps={{ span: 3 }}
                disabled={updateStatus}
                debounceTime={30 * 1000}
                request={async ({ keyWords = '' }) => {
                  var labelValues: any = [];
                  await getCountry
                    .run({ field: 'country', key: keyWords })
                    .then((data) => {
                      labelValues = data;
                    });
                  return labelValues;
                }}
              />

              <ProFormDatePicker
                name="patentTime"
                label="授权公告日"
                colProps={{ span: 3 }}
                disabled={updateStatus}
                rules={[{ required: true, message: '请选择' }]}
              />
            </ProForm.Group>
            <ProForm.Group title={'佐证材料'}>
              <ProFormSelect
                name="researchDire"
                disabled
                label="研究方向"
                colProps={{
                  span: 8,
                }}
                fieldProps={{
                  options: findAllDirection?.data || [],
                }}
                hidden={true}
              />
              <ProFormSelect
                options={getAllLabel?.data}
                mode="tags"
                name="labels"
                label="授权专利标签"
                colProps={{ span: 8 }}
                disabled={updateStatus}
                hidden={localStorage.getItem('identity') !== '管理员'}
                addonAfter={
                  <ModalForm<{
                    year: string;
                    labelName: string;
                  }>
                    title="新增标签"
                    trigger={<a>新增标签</a>}
                    autoFocusFirstInput
                    modalProps={{
                      onCancel: () => console.log('run'),
                    }}
                    submitTimeout={2000}
                    onFinish={async (values) => {
                      addLabelDetail.run(values);
                      return true;
                    }}
                  >
                    <ProForm.Group>
                      <ProFormDatePicker.Year
                        width="md"
                        name="year"
                        label="标签年份"
                        required
                      />
                      <ProFormText
                        width="md"
                        name="labelName"
                        label="标签名称"
                        required
                      />
                    </ProForm.Group>
                  </ModalForm>
                }
              />
            </ProForm.Group>
            {/* <ProForm.Group>
                      <ProFormTextArea
                        name="remarks"
                        label="专利简介"
                        fieldProps={{
                          rows: 2,
                        }}
                        disabled={updateStatus}
                        colProps={{ span: 15 }}
                      />
                    </ProForm.Group> */}
            <ProFormGroup>
              <ModalForm
                title="上传材料"
                trigger={
                  <Button icon={<UploadOutlined />} type="link">
                    上传材料（上传专利授权证书正反面，以专利名称命名）
                  </Button>
                }
                autoFocusFirstInput
                submitTimeout={2000}
                onFinish={async (values) => true}
              >
                {/* TbaleExplainMap['STANDARD'] 要修改 */}
                <ProCard title={TbaleExplainMap['PATENT']}>
                  {/* 有小问题，需要修改成pro的dragger */}
                  <Dragger {...props} maxCount={1}>
                    <p className="ant-upload-drag-icon">
                      <InboxOutlined />
                    </p>
                    <p className="ant-upload-text">
                      单击或拖动文件到此区域进行上传
                    </p>
                    <p className="ant-upload-hint">请上传一个文件</p>
                  </Dragger>
                </ProCard>
              </ModalForm>
              <Button
                type="link"
                onClick={() => {
                  findPaperDetailById?.data?.annexPath
                    ? window.open(findPaperDetailById?.data?.annexPath)
                    : message.info('请上传材料');
                }}
                icon={<FileSearchOutlined />}
              >
                查看材料
              </Button>
            </ProFormGroup>
          </ProForm>
        )
      }
    >
      {localStorage.getItem('isEdit') === '查看' ? <div></div> : null}

      <Modal
        title="请确认人员！"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        forceRender
      >
        <Table
          size="small"
          pagination={{ hideOnSinglePage: true, pageSize: 10 }}
          rowKey={'webId'}
          rowSelection={{
            onChange: (
              selectedRowKeys: React.Key[],
              selectedRows: DataType[],
            ) => {
              setSelectKeys(selectedRowKeys);
            },
            selectedRowKeys: selectKeys,
          }}
          columns={[
            {
              title: '工号',
              dataIndex: 'username',
              key: 'username',
            },
            {
              title: '姓名',
              dataIndex: 'realName',
              key: 'realName',
            },
            {
              title: '人员类型',
              dataIndex: 'userType',
              key: 'userType',
            },
          ]}
          dataSource={modalDataSource}
        />
      </Modal>
    </PageContainer>
  );
};
